package com.fubowen.lepton.ui.container.children.bookmark.recycler

import android.annotation.SuppressLint
import android.net.Uri
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.fubowen.lepton.bean.BookmarkBean
import com.fubowen.lepton.conf.AnnotationConfig
import com.fubowen.lepton.databinding.FragmentBookmarkListItemBinding
import com.fubowen.lepton.ui.container.children.bookmark.recycler.listener.OnItemClickListener
import java.io.File

class BookmarkViewHolder(
    private var binding: FragmentBookmarkListItemBinding,
    onItemClickListener: OnItemClickListener?
) : RecyclerView.ViewHolder(binding.root) {

    private val title: TextView = binding.bookmarkItemTitle
    private var url: TextView = binding.bookmarkItemUrl
    private var isChecked: CheckBox = binding.bookmarkItemSelectable
    private var icon: ImageView = binding.bookmarkItemIcon

    init {
        onItemClickListener?.apply {
            binding.bookmarkItemSelectable.setOnClickListener {
                onSelectableClick(
                    binding.root,
                    it
                )
            }
            binding.bookmarkItemToTop.setOnClickListener { onToTopClick(binding.root, it) }
            binding.root.setOnClickListener { onItemClick(binding.root) }
            binding.bookmarkItemMore.setOnClickListener { onMoreMenuClick(binding.root, it) }
            binding.root.setOnLongClickListener{
                onMoreMenuClick(binding.root, it)
                true
            }
        }
    }

    fun bind(item: BookmarkBean?) {
        item?.let {
            title.text = it.title
            bindUrl(it)
            bindIcon(it)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindUrl(item: BookmarkBean) = when (item.type) {
        BookmarkBean.TYPE_URL -> url.text = item.host
        else -> url.text = "${item.childCount}个书签"
    }

    private fun bindIcon(item: BookmarkBean) {
        if (item.icon.isNullOrEmpty()) {
            return
        }
        when (item.iconSource) {

            AnnotationConfig.ICON_SOURCE_URL -> {
                val file = Uri.fromFile(File(item.icon))
                icon.setImageURI(file)
            }

            AnnotationConfig.ICON_SOURCE_RESOURCE -> {
                val id = item.icon!!.toInt()
                icon.setImageResource(id)
            }

            AnnotationConfig.ICON_SOURCE_STRING -> {}
        }
    }
}